package com.hejun.jwt_security.utils;

import io.jsonwebtoken.*;

import java.util.Date;

public class JwtUtils {

    private static String key="hj-jwt";

    public static String getToken(String  username){
        return Jwts.builder().setHeaderParam("type", "jwt")
                .setExpiration(new Date(System.currentTimeMillis() + 2 * 60 * 60 * 1000))
                .setSubject(username)
                .signWith(SignatureAlgorithm.HS256, key).compact();
    }

    public static  Boolean validate(String token){
        try {
            Jwts.parser().setSigningKey("hj-jwt").parseClaimsJws(token).getBody();//拿到token载荷
        } catch (ExpiredJwtException e) {
            throw new RuntimeException("token过期");
        } catch (UnsupportedJwtException e) {
            throw new RuntimeException("不支持的Token");
        } catch (MalformedJwtException e) {
            throw new RuntimeException("错误的格式Token");
        } catch (SignatureException e) {
            throw new RuntimeException("签名错误");
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("参数不合法，钥匙不对");
        }
        return true;
    }

    public static String getUsername(String token){
        return Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().getSubject();
    }
}
